"""
Author        yongfa
Date          2023-08-31 03:37:35
LastEditTime  2023-09-08 07:12:13
LastEditors   yongfa
Description   数据模型
"""

from datetime import datetime, timedelta

from app.extensions.sqlalchemy import db, EntityModel as Base
from app.extensions.utils import get_uuid
from app.extensions.utils.encryption import Prpcrypt


class EmailInfo(Base):
    """邮箱信息"""
    __tablename__ = "resume_email_info"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    company_id = db.Column(db.Integer, db.ForeignKey("company.id"), comment='公司ID')
    email = db.Column(db.String(100), nullable=False, index=True, comment='邮箱')
    email_protocol = db.Column(db.String(20), nullable=False, comment='邮箱登录协议')
    email_host = db.Column(db.String(50), nullable=False, comment='邮箱HOST')
    email_port = db.Column(db.String(10), nullable=False, comment='邮箱端口')
    email_password_hash = db.Column(db.String(64), comment='邮箱密码')
    email_ssl = db.Column(db.Boolean, default=False, comment='是否使用SSL')
    status = db.Column(db.Boolean, default=True, comment='状态')

    @property
    def email_password(self):
        aes = Prpcrypt()
        email_password = aes.decrypt(self.email_password_hash)
        return email_password

    @email_password.setter
    def email_password(self, email_password='123456'):
        aes = Prpcrypt()
        self.email_password_hash = aes.encrypt(email_password)

    @property
    def exclude_fields(self):
        return super().exclude_fields + ['email_password_hash']


class ResumeEmailTask(Base):
    """邮箱解析任务"""
    __tablename__ = "resume_email_task"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    company_id = db.Column(db.Integer, comment='公司ID')
    company_email_id = db.Column(db.Integer, comment='邮箱ID')
    status = db.Column(db.SmallInteger, default=0, comment='任务状态')
    filter_conditions = db.Column(db.JSON, comment='筛选条件')
    process_mail_num = db.Column(db.Integer, comment='处理邮件数量')
    callback_url = db.Column(db.String(255), comment='结果回调地址')
    message = db.Column(db.String(255), comment='处理状态说明')
    celery_task_id = db.Column(db.String(64), comment='celery任务ID')

    @classmethod
    def get_recent_task(cls, company_email_id: int, minutes: int = 3):
        """最近任务"""
        task = cls.query.filter(
            cls.company_email_id == company_email_id,
            cls.create_time >= datetime.now() - timedelta(minutes=minutes)
        ).first()
        return task


class ResumeEmail(Base):
    """邮件内容"""
    __tablename__ = "resume_email"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    code = db.Column(db.String(50), nullable=False, index=True, comment='邮件唯一编号')
    email_info_id = db.Column(db.Integer, comment='邮箱ID')
    mail_id = db.Column(db.String(20), comment='系统邮件ID')
    email_from = db.Column(db.String(100), comment='邮件发送人')
    email_from_name = db.Column(db.String(100), comment='邮件发送人姓名')
    email_from_time = db.Column(db.String(100), comment='邮件发送时间')
    email_subject = db.Column(db.String(200), comment='邮件主题')
    email_content = db.Column(db.Text, comment='邮件内容')
    file_name = db.Column(db.String(255), comment='邮件附件名称')
    file_source_url = db.Column(db.String(255), comment='邮件附件源链接')
    file_local_url = db.Column(db.String(255), comment='邮件附件本地链接')
    language = db.Column(db.String(30), comment='语言')
    status = db.Column(db.SmallInteger, default=0, index=True, comment='邮件处理状态')
    message = db.Column(db.String(255), comment='处理状态说明')

    def __repr__(self):
        return "<ResumeEmail %r>" % self.code

    def __init__(self, *args, **kwargs) -> None:
        if self.code is None:
            """编码"""
            self.code = get_uuid()

    def to_dict(self, *args, **kwargs):
        exclude_fields = self.exclude_fields + ['email_content']
        res = super().to_dict(exclude_fields=exclude_fields)
        res['email_content'] = self.email_content[1:128] + '......'
        return res

    def list_to_dict(self, *args, **kwargs):
        res = self.to_dict(*args, **kwargs)
        return res


class ResumeParserTask(Base):
    __tablename__ = "resume_parser_task"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    resume_email_id = db.Column(db.Integer, comment='邮件ID')
    company_id = db.Column(db.Integer, comment='公司ID')
    resume_type = db.Column(db.Integer, default=0, comment='解析类型: 0: 文本 1: 文件')
    resume_text = db.Column(db.Text, comment='解析文本')
    resume_url = db.Column(db.String(511), comment='解析文件链接')
    resume_platform = db.Column(db.Integer, default=0, comment='简历来源平台: 0: 自定义')
    parser_status = db.Column(db.SmallInteger, default=0, index=True, comment='解析处理状态')
    parser_message = db.Column(db.String(255), comment='处理状态说明')
    parser_spend = db.Column(db.Integer, default=0, comment='解析耗时: S')
    parser_times = db.Column(db.Integer, default=0, comment='解析次数')
    callback_url = db.Column(db.String(511), comment='结果回调地址')
    callback_status = db.Column(db.Integer, default=0, comment='结果回调状态, 0: 失败 1: 成功')
    callback_times = db.Column(db.Integer, default=0, comment='结果回调次数')
    celery_task_id = db.Column(db.String(64), comment='celery任务ID')
    resume_content_id = db.Column(db.Integer, index=True, comment='简历内容ID')


class ResumeContent(Base):
    __tablename__ = "resume_content"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    code = db.Column(db.String(50), nullable=False, index=True, comment='简历唯一编号')
    language = db.Column(db.String(30), comment='语言')
    resume_name = db.Column(db.String(200), comment='投递简历姓名')
    source_text = db.Column(db.Text, comment='原始简历内容')
    parser_text = db.Column(db.Text, comment='解析后简历内容')

    def __init__(self, *args, **kwargs) -> None:
        if self.code is None:
            """编码"""
            self.code = get_uuid()
